package com.bestcem.xm.label.grpc.service;

import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.label.grpc.v1.services.GetHealthInfoResponse;
import com.bestcem.xm.label.grpc.v1.services.HealthInfo;
import com.bestcem.xm.label.grpc.v1.services.SystemServiceGrpc;
import com.bestcem.xm.label.service.SystemService;
import com.bestcem.xm.label.service.dto.HealthInfoDTO;
import com.google.protobuf.Empty;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 系统服务
 * @date 2021-05-28
 */
@GrpcService
public class SystemGrpcService extends SystemServiceGrpc.SystemServiceImplBase {

    /**
     * 系统服务
     */
    @Autowired
    private SystemService systemService;

    /**
     * 健康检查
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void getHealthInfo(Empty request, StreamObserver<GetHealthInfoResponse> responseObserver) {
        GetHealthInfoResponse.Builder builder = GetHealthInfoResponse.newBuilder();

        ServiceResult<HealthInfoDTO> result = systemService.getHealthInfo();
        if (!result.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(result.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        HealthInfo healthInfo = this.toHealthInfo(result.getData());
        responseObserver.onNext(builder.setStatus(RpcStatusResult.success()).setInfo(healthInfo).build());
        responseObserver.onCompleted();
    }

    /**
     * 数据转换
     *
     * @param healthInfoDTO
     * @return
     */
    private HealthInfo toHealthInfo(HealthInfoDTO healthInfoDTO) {
        HealthInfo.Builder builder = HealthInfo.newBuilder();
        if (healthInfoDTO == null) {
            return builder.build();
        }
        GRpcUtil.fillDefaultValue(healthInfoDTO);

        return builder.setStatusValue(healthInfoDTO.getStatus()).build();
    }
}
